package com.github.echarts.util;


import com.github.echarts.json.GsonOption;

import java.io.*;


public class EChartJsUtils {

    //echarts-convert.js所在目录，实际使用可以写在.yml文件里，然后使用@value动态获取
    private static String echartConverJsPath = "D:\\test-phant\\echarts-convert.js";
    //phantomjs所在目录，到bin那一层，实际使用可以写在.yml文件里，然后使用@value动态获取
    private static String phantomHomePath = "D:\\tools\\echart-phantomjs\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe";

    private static String localPath;


    static {
        localPath = EChartJsUtils.class.getResource("").getPath().replaceFirst("/", "") + "echart" + File.separator ;
        phantomHomePath = localPath +"phantomjs"+ File.separator +"win"+ File.separator +"phantomjs.exe";
        echartConverJsPath = localPath + "echarts-convert.js";
    }



    /**
     * 根据echart 参数生成 echart 图片
     * @param options
     * @param width
     * @param height
     * @return
     */
    public static String processEChart(GsonOption options, int width, int height) {
        //生成png文件名
        String imgPath = localPath + System.currentTimeMillis() + ".png";
        Process process = null;
        try {
            String jsonPath = localPath +  System.currentTimeMillis() + ".json";
            //生成初始化json文件
            writeFile(options.toString(), jsonPath);
            //拼接phantomjs命令行
            String cmd = phantomHomePath + " " + echartConverJsPath +
                    " -infile " + jsonPath +
                    " -outfile " + imgPath +
                    " -width " + width +
                    " -height " + height;
            System.out.println("####### 开始执行command命令： " + cmd);

            process = Runtime.getRuntime().exec(cmd);
            readProcess(process);
            // 关闭进程资源对象
            process.waitFor();
            //删除临时json文件
            deleteDirFile(jsonPath);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != process) {
                process.destroy();
            }
        }
        return  imgPath;
    }

    public static void readProcess(Process process) throws Exception{
        InputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            //取得命令结果的输出流
            fis=process.getInputStream();
            //用一个读输出流类去读
            isr=new InputStreamReader(fis);
            //用缓冲器读行
            br=new BufferedReader(isr);
            String line=null;
            //直到读完为止
            while((line=br.readLine())!=null) {
                System.out.println(line);
            }
        } finally {
            if (null != fis) {
                fis.close();
            }
            if (null != isr) {
                isr.close();
            }
            if (null != br) {
                br.close();

            }
        }
    }

    public static String writeFile(String options, String dataPath) throws IOException{
        System.out.println("########## 内容写入文件 #########");
        File file = createDirFile(dataPath);
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
            BufferedWriter fileWrite = new BufferedWriter(write);
            fileWrite.write(options);
            fileWrite.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return dataPath;
    }

    public static File createDirFile(String path) throws IOException {
        System.out.println("########## 创建文件 #########");
        // 文件路径（路径+文件名）
        File file = new File(path);
        // 文件不存在则创建文件，先创建目录
        if (!file.exists()) {
            File dir = new File(file.getParent());
            dir.mkdirs();
            file.createNewFile();
        }
        return file;
    }

    public static Boolean deleteDirFile(String path) throws IOException {
        System.out.println("########## 删除文件 #########");
        // 文件路径（路径+文件名）
        File file = new File(path);
        // 文件不存在则创建文件，先创建目录
        if (file.exists()) {
            return file.delete();
        }
        return Boolean.FALSE;
    }


    public static void checkOS() throws Exception {
        //获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        if (osName.startsWith("Mac OS")) {

        } else if (osName.startsWith("Windows")) {

        } else {
            // Unix or Linux的

        }
    }

}


